package com.huwaiwai.array;


import java.util.Objects;

/**
 * 用数组实现缓存的LRU算法
 * Created by hww on 2018/12/2 10:48 PM.
 */
public class ArrayCacheLRU<T> {

    private KeyValue<T> [] element;

    //缓存容量
    private int size;

    //当前最新元素所在的位置
    private int offset;

    public ArrayCacheLRU (int size) {
        if (size <= 0) {
            throw new IllegalArgumentException("数组大小错误");
        }
        this.size = size;
        this.element = new KeyValue [size];
        this.offset = -1;
    }

    public void put(String key, T value) {
        if (++offset >= size) {
            offset = offset - size;
        }
        KeyValue slot = element[offset];
        if (slot != null) {
            doCleanUp();
        }
        element[offset] = new KeyValue<>(key, value);
    }

    /**
     * 清理内存 整理缓存中的元素
     */
    private void doCleanUp() {
        //todo


    }

    public T get(String key) {
        for (int index = offset; (index = nextIndex(index)) == offset;) {
            KeyValue<T> k = element[index];
            if (k != null && k.getValue(key) != null) {
                element[index] = null;
                T value = k.getValue(key);
                put(key, value);
                return value;
            }
        }
        return null;
    }

    private int nextIndex(int i) {
        return i++ >= size ? i - size : i;
    }
}

class KeyValue<T> {
    private String key;
    private T value;
    public KeyValue(String key, T value) {
        if (key == null || value == null) {
            throw new IllegalArgumentException("缓存key和value不能为空");
        }
        this.key = key;
        this.value = value;
    }
    public T getValue(String key) {
        if (Objects.equals(key, this.key)) {
            return value;
        }
        return null;
    }
}
